package tcp_proxy_middleware

import (
	"gin-gateway/core/utils"
	"log"
	"gin-gateway/reverse_proxy"
)

func TCPFlowCountMiddleware() func(c *reverse_proxy.TcpSliceRouterContext) {
	return func(c *reverse_proxy.TcpSliceRouterContext) {
		serviceDetail := GetServiceDetail(c)

		//统计项 1 全站 2 服务 3 租户
		totalCounter, err := utils.FlowCountManager.GetRedisCounter(utils.FlowTotal)
		if err != nil {
			_, err := c.Conn.Write([]byte(err.Error()))
			if err != nil {
				log.Println("TCPFlowCountMiddleware GetRedisCounter error", err)
			}
			c.Abort()
			return
		}
		totalCounter.Increase()

		serviceCounter, err := utils.FlowCountManager.GetRedisCounter(utils.FlowServicePrefix + serviceDetail.Info.ServiceName)
		if err != nil {
			write, err := c.Conn.Write([]byte(err.Error()))
			if err != nil {
				log.Println(write, err)
				return
			}
			c.Abort()
			return
		}
		serviceCounter.Increase()
		c.Next()
	}
}
